package com.yeshine.opendata.web;

import com.yeshine.opendata.core.AppException;
import com.yeshine.opendata.core.ControllerBase;
import com.yeshine.opendata.entity.SysDictionary;
import com.yeshine.opendata.entity.SysVisitLog;
import com.yeshine.opendata.service.ISysVisitLogService;
import com.yeshine.opendata.utils.JsonUtil;
import com.yeshine.opendata.utils.ReflectUtil;
import com.yeshine.opendata.utils.Result;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.aop.ProxyMethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 日志处理类
 * Created by taohj on 2014/10/13.
 */


public class LogHandlerAdapter {



    Logger logger = Logger.getLogger(this.getClass());


   @Autowired
    private ISysVisitLogService logService;


    public Object invoke(ProceedingJoinPoint obj) throws Throwable {

        ProxyMethodInvocation methodInvocation = (ProxyMethodInvocation) ReflectUtil.getFieldValue(obj, "methodInvocation");
        Method method = methodInvocation.getMethod();
        System.out.println("================>Class:" + method.getDeclaringClass().getName() + "----MethodName:" + method.getName());
        logger.info("================>Class:" + method.getDeclaringClass().getName() + "----MethodName:" + method.getName());



        HttpServletRequest request= ControllerBase.getRequest();
        HttpSession session= ControllerBase.getSession();


        SysVisitLog log=new SysVisitLog();
        log.setSessionid(session.getId());
        log.setUser(null);
        log.setSessionType(new SysDictionary(0));

        log.setURL(request.getRequestURI());

        if(log.getURL().equals("/dataFiledownload")){
            log.setAction(new SysDictionary(221));
        }


        log.setTime(new Date());
        log.setParam(JsonUtil.toString(request.getParameterMap()));
        log.setIP(getRemortIP(request));
        Result<SysVisitLog> result=logService.create(log);
        if(!result.isSuccess()){
            throw new AppException("日志记录失败："+JsonUtil.toString(log));
        }else{
            System.out.println("日志记录成功："+JsonUtil.toString(log));
        }
         return obj.proceed();




    }

    public String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }


}
